<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Main extends CI_Controller {

    public function index() {
        $this->destroySession();
        $this->loadLoginPage();
    }

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model', '', TRUE);
        $this->load->model('nivel_model', '', TRUE);
        $this->load->model('setor_model', '', TRUE);
    }
        
           
    public function login() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
        
        $result = $this->user_model->login($this->input->post('username'), $this->input->post('password'));
        
        
        if ($this->form_validation->run() == FALSE || $result == false) {
            //Field validation failed.  User redirected to login page
            $this->destroySession();
            $this->loadLoginPage();
        } else {
            //Go to private area
            $this->setLoggedIn($result);
            redirect('main/privateArea', 'refresh');
        }
    }

    private function loadLoginPage() {
        $this->load->view('main/header');
        $this->load->view('main/login_page');
    }

    public function privateArea() {
        $session = $this->returnSession();
        
        $array['niveis'] = $this->nivel_model->listarTodos();
        $array['setores'] = $this->setor_model->listarTodos();
        $stdObj = $this->user_model->retornarAcesso($session['id']);
        $array['access'] = $stdObj->usuario_acesso;
        $this->loadPrivatePage($array, $session);
    }

    public function loadPrivatePage($array, $session) {
        if($session != null):
            //$this->load->view('header');
            $this->load->view('main/private_page', $array);
            else:
                echo "Voce nao tem permissao para acessar essa pagina!";
        endif;
        
    }

    
}